package com.twan.kotlinbase.ui

import android.view.KeyEvent
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.OnClick
import butterknife.OnEditorAction
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.twan.kotlinbase.R
import com.twan.kotlinbase.app.BaseDataBindingActivity
import com.twan.kotlinbase.bean.*
import com.twan.kotlinbase.databinding.*
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.util.*
import com.wx.goodview.GoodView
import kotlinx.android.synthetic.main.activity_discovery_detail.*
import kotlinx.android.synthetic.main.activity_discovery_detail.refreshLayout
import kotlinx.android.synthetic.main.fragment_service.*
import kotlinx.android.synthetic.main.item_comment.*
import kotlinx.android.synthetic.main.tab2_fragment_user.*
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse


class DiscoveryDetailActivity : BaseDataBindingActivity<ActivityDiscoveryDetailBinding>(){
    lateinit var mDiscovery:Discovery
    lateinit var goodView: GoodView
    override fun getLayout(): Int {
        return R.layout.activity_discovery_detail
    }

    override fun initEventAndData() {
        whiteToolbar("动态详情")
        goodView = GoodView(this)
        showUi()
        initRefresh()
        initCommentRv()
    }

    fun initRefresh(){
        refreshLayout.setRefreshHeader(ClassicsHeader(this))
        refreshLayout.setRefreshFooter(ClassicsFooter(this))
        refreshLayout.setOnRefreshListener {
            currentPage=1
            getData()
        }
        refreshLayout.setEnableLoadMore(true)
        refreshLayout.setOnLoadMoreListener { getData() }
    }

    fun showUi(){
        mDiscovery = intent.getSerializableExtra("data") as Discovery
        mBinding.item=mDiscovery
        GlideUtils.load(this,mBinding.ivAvater,mDiscovery.avatarUrl)
        mBinding.tvShijian.text=DateUtil.formatDate2String(mDiscovery.releaseTime)
        mBinding.tvLike.setOnClickListener {
            mBinding!!.tvLike.text=(mDiscovery.likeCount+1).toString()
            goodView.setText("+1")//goodView.setImage(getResources().getDrawable(R.mipmap.good_checked));
            goodView.show(it)
            dianzan(mDiscovery.id)
        }
        //九宫格图片
        rv_pic.layoutManager=GridLayoutManager(this,3)
        rv_pic.adapter = object : BaseQuickAdapter<String,BaseViewHolder>(R.layout.item_pic, mDiscovery.imagesUrl){
            override fun convert(holder: BaseViewHolder, url: String) {
                var iv_pic =holder.getView<ImageView>(R.id.iv_pic)
                GlideUtils.loadCorner(this@DiscoveryDetailActivity,iv_pic,url.toString())
                iv_pic.setOnClickListener {
                    XpopupUtils.previewMultiImgs(this@DiscoveryDetailActivity,holder.adapterPosition,iv_pic,mDiscovery.imagesUrl as MutableList<Any>)
                }

            }
        }
    }

    fun dianzan(momentsId:String){
        RxHttpScope().launch {
            RxHttp.postJson("moment/like").add("likedPostId", MyUtils.getUserid()).add("momentsId",momentsId).toResponse<Any>().await()
        }
    }

    @OnEditorAction(R.id.edt_comment)
    fun onEditorAction(edt:EditText, actionId:Int,  event: KeyEvent) {


    }

    @OnClick(R.id.btn_send)
    fun send(){
        var ischeck = InputUtils.checkEmpty(edt_comment)
        if (!ischeck) ToastUtils.showShort("请写点高见吧")
        RxHttpScope().launch {
            RxHttp.postJson("comment/save")
                    .add("commentText", edt_comment.text.toString())
                    .add("commentTime", TimeUtils.getNowString())
                    .add("id", "")
                    .add("momentsId", mDiscovery.id)
                    .add("nickName", MyUtils.getLoginInfo()?.nickName)
                    .add("userId", MyUtils.getUserid())
                    .toResponse<Any>().await()
            getData(true)
            edt_comment.setText("")
        }
    }

    //显示评论
    lateinit var mAdapter:BaseQuickAdapter<MyComment, BaseDataBindingHolder<ItemCommentBinding>>
    fun initCommentRv(){
        rv_comment.adapter=object : BaseQuickAdapter<MyComment, BaseDataBindingHolder<ItemCommentBinding>>(R.layout.item_comment){
            override fun convert(holder: BaseDataBindingHolder<ItemCommentBinding>, item: MyComment) {
                holder.dataBinding!!.item=item
                GlideUtils.loadCicle(this@DiscoveryDetailActivity,holder.dataBinding!!.ivAvater,item.avatarUrl)
                holder.dataBinding!!.tvTime.text=DateUtil.formatDate2String(item.commentTime)
                initComment(item.replyList)
            }

        }.also {
            mAdapter=it
            getData()
        }
    }

    var currentPage=1
    fun getData(isRefresh:Boolean=false){
        if (isRefresh) currentPage=1
        RxHttpScope(this,refreshLayout).launch {
            var req= RxHttp.get("comment/getByCondition")
                .add("momentId",mDiscovery.id)
                .add("pageSize",20)
                .add("currentPage",currentPage++)
                .toResponse<PageData<MyComment>>().await()
            if (currentPage==2) mAdapter.setList(req.content)
            else  mAdapter.addData(req.content)
        }
    }

    //评论了别人的评论
    fun initComment(replyList:MutableList<Reply>?){
        replyList?.run {
            rv_comment_rep.adapter=object : BaseQuickAdapter<Reply, BaseDataBindingHolder<ItemCommentReplyBinding>>(R.layout.item_comment_reply,replyList){
                override fun convert(holder: BaseDataBindingHolder<ItemCommentReplyBinding>, item: Reply) {
                    holder.dataBinding!!.item=item
                    GlideUtils.loadCicle(this@DiscoveryDetailActivity,holder.dataBinding!!.ivAvater,"")
                    holder.dataBinding!!.tvTime.text=DateUtil.formatDate2String(item.replyTime)
                }

            }
        }
    }
}